// 计算热量
import type { UserFiltersI } from '@/types/user'
import { getStringToNumber } from '@/utils'

/**
 * 计算基础代谢率
 * @param sex 性别
 * @param ageStr 年龄
 * @param heightStr 身高
 * @param weightStr 体重
 * @returns 基础代谢率
 */
export const calculateBMR = (sex: number, ageStr: string, heightStr: string, weightStr: string) => {
  const age = getStringToNumber(ageStr, '岁')
  const height = getStringToNumber(heightStr, 'cm')
  const weight = getStringToNumber(weightStr, 'kg')

  if (sex == 1) {
    return 10 * weight + 6.25 * height - 5 * age + 5
  } else {
    return 10 * weight + 6.25 * height - 5 * age - 161
  }
}

/**
 * 计算每日总能量消耗
 * @param bmr 基础代谢率
 * @param sport_ability 运动能力
 * @returns 每日总能量消耗
 */
export const calculateTDEE = (bmr: number, sport_ability: number) => {
  return bmr * sport_ability
}

/**
 * 计算每日运动消耗
 * @param tdee 每日总能量消耗
 * @param bmr 基础代谢率
 * @returns 每日运动消耗
 */
export const calculateExerciseConsume = (bmr: number, tdee: number) => {
  return tdee - bmr
}

/**
 * 计算体重变化
 * @param weightStr 体重
 * @param targetWeightStr 目标体重
 * @returns 体重变化
 */
const weightChange = (weightStr: string, targetWeightStr: string) => {
  const weight = getStringToNumber(weightStr, 'kg')
  const targetWeight = getStringToNumber(targetWeightStr, 'kg')
  return Math.abs(weight - targetWeight)
}

/**
 * 计算计划天数
 * @param weightStr 体重
 * @param targetWeightStr 目标体重
 * @returns 计划天数
 */
export const calculateDays = (weightStr: string, targetWeightStr: string) => {
  return weightChange(weightStr, targetWeightStr) * 7
}

/**
 * 计算每日摄入量
 * @param target 目标
 * @param tdee 每日总能量消耗
 * @param weightStr 体重
 * @param targetWeightStr 目标体重
 * @returns 每日摄入量
 */
export const calculateIngestion = (
  target: number,
  tdee: number,
  weightStr: string,
  targetWeightStr: string,
) => {
  const change = weightChange(weightStr, targetWeightStr)
  const days = calculateDays(weightStr, targetWeightStr)

  if (target == 0) {
    return tdee + (7700 * change) / days
  } else {
    return tdee - (7700 * change) / days
  }
}

/**
 * 根据筛选条件计算每日摄入量
 * @param filter 筛选条件
 * @returns 每日摄入量
 */
export const calculateDailyIngestion = (filter: UserFiltersI) => {
  // 1. 计算基础代谢率
  const bmr = calculateBMR(filter.sex, filter.age, filter.height, filter.weight)
  // 2. 计算每日总能量消耗
  const tdee = calculateTDEE(bmr, filter.sport_ability)
  // 3. 计算每日摄入量
  const ingestion = calculateIngestion(filter.target, tdee, filter.weight, filter.target_weight)
  // 4. 返回每日摄入量
  return ingestion
}

/**
 * 根据筛选条件计算每日消耗
 * @param filter 筛选条件
 * @returns 每日消耗
 */
export const calculateDailyConsume = (filter: UserFiltersI) => {
  // 1. 计算基础代谢率
  const bmr = calculateBMR(filter.sex, filter.age, filter.height, filter.weight)
  // 2. 计算每日总能量消耗
  const tdee = calculateTDEE(bmr, filter.sport_ability)
  // 3. 计算每日运动消耗
  return calculateExerciseConsume(bmr, tdee)
}
